// pages/TradingAreaCenter/addCouponBag.js
const controller = require("../controllers/Controller").controller

var dateTimePicker = require('../../utils/dateTimePicker.js');


const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    title: "",
    icon1: "https://xinlingshoushangquan.oss-cn-shenzhen.aliyuncs.com/account/20210513/842452706747482112.png",
    icon2: "https://xinlingshoushangquan.oss-cn-shenzhen.aliyuncs.com/account/20210513/842452919725850624.png",
    payTypeList: [{
      name: "单次购买",
      id: 1
    }, {
      name: "无限制",
      id: 0
    }],
    shopGroupList: [],
    shopList: [],
    type: "",
    img: "",
    startTime: "",
    endTime: "",
    baseUrl: "",
    payType: 1,
    num: "",
    index: "",
    shopGroupId: "",
    shopId: "",
    price: "",
    detailImg: "",
    sort: "",
    couponList: [],
    cardList: [],
    shopGroupName: "",
    useRules: "",
    noSelectIcon: 'https://xinlingshoushangquan.oss-cn-shenzhen.aliyuncs.com/account/20210513/842452706747482112.png',
    selectedIcon: 'https://xinlingshoushangquan.oss-cn-shenzhen.aliyuncs.com/account/20210513/842452919725850624.png',
    activitySelectList: [{
      name: "系统默认",
      id: 0
    }, {
      name: "自定义",
      id: 1
    }],
    activityRuleIndex: 0
  },
  onShow: function () {
    this.totalPrice()
  },
  onLoad: function (options) {
    this.getDateTimeData()
    this.getShopGroupList()

    this.setData({
      type: options.type ? JSON.parse(options.type) : '',
      baseUrl: app.globalData.IMG_URL
    })
    if (this.data.type === 0) {
      this.setData({
        title: "新增一卡通"
      })
    } else {
      this.setData({
        title: "新增商圈爆品"
      })
    }
    if (options.id) {
      this.getBagDetail(options.id)
      if (options.sort) {
        this.setData({
          isUpdata: true
        })
      }
      console.log(this.data.type)
      if (this.data.type == 2) {
        this.setData({
          id: options.id,
          title: "店铺爆款详情",
        })
        console.log("执行1")
      } else if (this.data.type == 3) {
        this.setData({
          id: options.id,
          title: "拼拼有米详情",
        })
        console.log("执行1")
      } else if (this.data.type == 4) {
        this.setData({
          id: options.id,
          title: "限时抵扣详情",
        })
        console.log("执行1")
      } else if (this.data.type == 5) {
        this.setData({
          id: options.id,
          title: "店铺超值礼包详情",
        })
        console.log("执行1")
      } else {
        this.setData({
          id: options.id,
          title: "一卡通详情",
        })
        console.log("执行2")
      }
    }

  },
  // 获取时间列表数据
  getDateTimeData() {
    const startYear = 2010
    const endYear = 2050
    // 获取完整的年月日 时分秒，以及默认显示的数组
    let startObj = dateTimePicker.dateTimePicker(startYear, endYear);
    let endObj = dateTimePicker.dateTimePicker(startYear, endYear);
    // 精确到时的处理，将数组的分秒去掉
    let startListArray = startObj.dateTimeArray;
    let startListNum = startObj.dateTime;
    let endListArray = endObj.dateTimeArray;
    let endListNum = endObj.dateTime;

    startListArray.splice(startListArray.length - 2, 2);
    startListNum.splice(startListNum.length - 2, 2);
    // 时，固定23
    endListArray.splice(endListArray.length - 3, 3, [23]);
    endListNum.splice(endListNum.length - 3, 3, [0]);

    this.setData({
      startListNum,
      startListArray,
      endListNum,
      endListArray,
    });
  },

  //获取开始时间
  bindStartTime(e) {
    let startListArray = this.data.startListArray
    let startListNum = this.data.startListNum
    // 避免大小月切换日选项错误
    if (startListNum[2] > startListArray[2].length - 1) startListNum[2] = 0
    let startTime = startListArray[0][startListNum[0]] + '-' + startListArray[1][startListNum[1]] + '-' + startListArray[2][startListNum[2]] + ' ' + startListArray[3][startListNum[3]] + ':00'
    this.setData({
      startListNum: e.detail.value,
      startTime
    })
  },

  //获取结束时间
  bindEndTime(e) {
    let endListArray = this.data.endListArray
    let endListNum = this.data.endListNum
    if (endListNum[2] > endListArray[2].length - 1) endListNum[2] = 0
    let endTime = endListArray[0][endListNum[0]] + '-' + endListArray[1][endListNum[1]] + '-' + endListArray[2][endListNum[2]] + ' ' + endListArray[3][endListNum[3]] + ':00'
    this.setData({
      endListNum: e.detail.value,
      endTime
    })
  },

  changeStartTimeColumn(e) {
    var arr = this.data.startListNum,
      dateArr = this.data.startListArray;

    arr[e.detail.column] = e.detail.value;
    dateArr[2] = dateTimePicker.getMonthDay(dateArr[0][arr[0]], dateArr[1][arr[1]]);

    this.setData({
      startListArray: dateArr,
      startListNum: arr
    });
  },
  changeEndTimeColumn(e) {
    var arr = this.data.endListNum,
      dateArr = this.data.endListArray;

    arr[e.detail.column] = e.detail.value;
    dateArr[2] = dateTimePicker.getMonthDay(dateArr[0][arr[0]], dateArr[1][arr[1]]);

    this.setData({
      endListArray: dateArr,
      endListNum: arr
    });
  },

  // 选择活动规则
  selectActivityRule(e) {
    if (this.data.isUpdata) {
      return
    }
    let index = e.currentTarget.dataset.index
    this.setData({
      activityRuleIndex: index
    })
  },


  // 获取使用规则
  getUseRules(e) {
    this.setData({
      useRules: e.detail.value
    })
  },

  toSelectAdd() {
    let list = this.data.couponList

    let shopGroupId = this.data.shopGroupId
    if (!shopGroupId) {
      wx.showToast({
        icon: "none",
        title: '请选择商圈',
        duration: 1500
      })
      return
    }

    if (this.data.type === 0) {
      wx.navigateTo({
        url: '/pages/TradingAreaCenter/selectCouponAdd?shopGroupId=' + shopGroupId + '&list=' + encodeURIComponent(JSON.stringify(list)),
      })
    } else {
      wx.navigateTo({
        url: '/pages/TradingAreaCenter/selectGiftAdd?shopGroupId=' + shopGroupId + "&shopId=" + this.data.shopId + '&list=' + encodeURIComponent(JSON.stringify(list)),
      })
    }
  },

  // 跳转添加引流卡
  toAddCard() {
    let list = this.data.cardList

    let shopGroupId = this.data.shopGroupId
    if (!shopGroupId) {
      wx.showToast({
        icon: "none",
        title: '请选择商圈',
        duration: 1500
      })
      return
    }
    wx.navigateTo({
      url: '/pages/TradingAreaCenter/selectCardAdd?shopGroupId=' + shopGroupId + '&list=' + encodeURIComponent(JSON.stringify(list)),
    })
  },

  //打开预览图片
  openBigImg() {
    if (!this.data.detailImg) {
      return
    }
    let that = this
    let list = []
    list.push(that.data.detailImg)
    wx.previewImage({
      current: that.data.detailImg,
      urls: list
    })
  },

  //优惠券重排
  repeatList() {
    let list = this.data.couponList
    let repeatList = []
    let couponMap = new Map()

    for (let i = 0; i < list.length; i++) {
      let coupon = list[i];
      let shopId = coupon.shopId;

      let sonCouponMap = undefined;
      if (couponMap.has(shopId)) {
        sonCouponMap = couponMap.get(shopId);
      } else {
        sonCouponMap = new Map();
        couponMap.set(shopId, sonCouponMap);
      }
      if (!sonCouponMap.has(coupon.id)) {
        sonCouponMap.set(coupon.id, coupon);
      }
    }
    couponMap.forEach(function (value, key) {
      let object = {}
      object.shopId = key;
      let couponList = [...value.values()];
      couponList.forEach(item => {
        if (item.effectiveStartTime) {
          item.effectiveStartTime = item.effectiveStartTime.slice(0, 10);
          item.effectiveEndTime = item.effectiveEndTime.slice(0, 10);
        }
      })
      object.shopName = couponList[0].shopName;
      object.couponList = couponList;

      repeatList.push(object);
    });

    this.setData({
      repeatList: repeatList
    })
  },

  // 引流卡重排
  repeatCardList() {
    let list = this.data.cardList
    let repeatList = []
    let couponMap = new Map()

    for (let i = 0; i < list.length; i++) {
      let card = list[i];
      let shopId = card.shopId;

      let sonCardMap = undefined;
      if (couponMap.has(shopId)) {
        sonCardMap = couponMap.get(shopId);
      } else {
        sonCardMap = new Map();
        couponMap.set(shopId, sonCardMap);
      }
      if (!sonCardMap.has(card.id)) {
        sonCardMap.set(card.id, card);
      }
    }
    couponMap.forEach(function (value, key) {
      let object = {}
      object.shopId = key;
      let cardList = [...value.values()];
      object.shopName = cardList[0].shopName;
      object.cardList = cardList;
      repeatList.push(object);
    });

    this.setData({
      repeatCardList: repeatList
    })
  },

  //获取价格
  getPrice(e) {
    let price = e.detail.value
    this.setData({
      price: price
    })
  },
  //获取排序值
  getSortNumber(e) {
    let sort = e.detail.value
    this.setData({
      sort: sort
    })
  },
  //减少优惠券
  reduceNum(e) {
    if (this.data.isUpdata) {
      return
    }
    let id = e.currentTarget.dataset.id
    let index = ""
    let list = this.data.couponList
    for (let i = 0; i < list.length; i++) {
      if (list[i].id == id) {
        index = i
      }

    }
    if (list[index].num >= 1) {
      list[index].num--
    } else {
      list.splice(index, 1)
    }

    this.setData({
      couponList: list
    })
    this.totalPrice()
    this.repeatList()
  },
  // 减少引流卡
  reduceCardNum(e) {
    if (this.data.isUpdata) {
      return
    }
    let id = e.currentTarget.dataset.id
    let index = ""
    let list = this.data.cardList
    for (let i = 0; i < list.length; i++) {
      if (list[i].id == id) {
        index = i
      }
    }
    if (list[index].num >= 1) {
      list[index].num--
    } else {
      list.splice(index, 1)
    }
    this.setData({
      cardList: list
    })
    this.totalPrice()
    this.repeatCardList()
  },

  //增加优惠券
  addNum(e) {
    if (this.data.isUpdata) {
      return
    }
    let id = e.currentTarget.dataset.id
    let index = ""
    let list = this.data.couponList
    for (let i = 0; i < list.length; i++) {
      if (list[i].id == id) {
        index = i
      }

    }
    list[index].num++
    this.setData({
      couponList: list
    })
    this.totalPrice()
    this.repeatList()
  },

  // 增加引流卡
  addCardList(e) {
    if (this.data.isUpdata) {
      return
    }
    let id = e.currentTarget.dataset.id
    let index = ""
    let list = this.data.cardList
    for (let i = 0; i < list.length; i++) {
      if (list[i].id == id) {
        index = i
      }
    }
    list[index].num++
    this.setData({
      cardList: list
    })
    this.totalPrice()
    this.repeatCardList()
  },

  //设置排序值
  setCouponSort(e) {
    let value = e.detail.value
    console.log(e)
    if (this.data.isUpdata) {
      return
    }
    let id = e.currentTarget.dataset.id
    let index = ""
    let list = this.data.couponList
    for (let i = 0; i < list.length; i++) {
      if (list[i].id == id) {
        index = i
      }
    }
    list[index].sort = value
    this.setData({
      couponList: list
    })
  },

  // 设置引流卡排序值
  setCardSort(e) {
    let value = e.detail.value
    console.log(e)
    if (this.data.isUpdata) {
      return
    }
    let id = e.currentTarget.dataset.id
    let index = ""
    let list = this.data.cardList
    for (let i = 0; i < list.length; i++) {
      if (list[i].id == id) {
        index = i
      }
    }
    list[index].sort = value
    this.setData({
      cardList: list
    })
  },

  //删除选中的优惠券
  delCoupon(e) {
    if (this.data.isUpdata) {
      return
    }
    let id = e.currentTarget.dataset.id
    let index = ""
    let list = this.data.couponList
    for (let i = 0; i < list.length; i++) {
      if (list[i].id == id) {
        index = i
      }
    }
    list.splice(index, 1)
    this.setData({
      couponList: list
    })
    this.totalPrice()
    this.repeatList()
  },

  // 删除选中引流卡
  delCard(e) {
    if (this.data.isUpdata) {
      return
    }
    let id = e.currentTarget.dataset.id
    let index = ""
    let list = this.data.cardList
    for (let i = 0; i < list.length; i++) {
      if (list[i].id == id) {
        index = i
      }
    }
    list.splice(index, 1)
    this.setData({
      cardList: list
    })
    this.totalPrice()
    this.repeatCardList()
  },


  //选择商圈
  bindShopGroupChange(e) {
    let index = e.detail.value
    this.setData({
      index: index,
      shopGroupId: this.data.shopGroupList[index].id,
      shopGroupName:this.data.shopGroupList[index].name
    })
    this.getShopList()
    this.setData({
      couponList: []
    })
    this.repeatList()
  },
  //选择商圈店铺
  bindShopChange(e) {
    let index = e.detail.value
    this.setData({
      index2: index,
      shopId: this.data.shopList[index].id
    })
    this.getShopList()
    this.setData({
      couponList: []
    })
    this.repeatList()
  },


  //选择支付限制
  selectPayType(e) {
    if (this.data.isUpdata) {
      return
    }
    let index = e.currentTarget.dataset.index
    this.setData({
      payType: this.data.payTypeList[index].id
    })
  },

  //获取礼一卡通数量
  getNumber(e) {
    console.log(e)
    this.setData({
      num: e.detail.value
    })
  },

  //获取商圈列表
  getShopGroupList() {
    let value = {}
    value.examineState = 0
    value.state = 0
    controller.myShopGroupList(value).then(res => {
      this.setData({
        shopGroupList: res.data
      })
    })
  },

  //根据商圈id获取商家列表 2.0
  getShopList() {
    let shopGroupId = this.data.shopGroupId
    controller.getShopList({
      shopGroupId: shopGroupId
    }).then(res => {
      this.setData({
        shopList: res.data
      })
    })
  },

  //获取名称
  getName(e) {
    this.setData({
      name: e.detail.value
    })
  },



  //计算礼包或一卡通总价值
  totalPrice() {
    let totalPrice = 0
    for (let i = 0; i < this.data.couponList.length; i++) {
      totalPrice = totalPrice + this.data.couponList[i].num * this.data.couponList[i].price
    }
    for (let i = 0; i < this.data.cardList.length; i++) {
      totalPrice = totalPrice + this.data.cardList[i].num * this.data.cardList[i].price
    }
    this.setData({
      cost: totalPrice
    })
  },


  //获取券礼包详情
  getBagDetail(id) {
    controller.getActivityDetail({
      couponBagId: id
    }).then(res => {
      let list = []
      if (res.data.couponMap) {
        let keys = Object.keys(res.data.couponMap)
        keys.forEach(item => {
          for (let i = 0; i < res.data.couponMap[item].length; i++) {
            list.push(res.data.couponMap[item][i])
          }
        })
      }
      this.setData({
        type: res.data.type,
        img: res.data.img,
        startTime: res.data.startTime.substr(0, 16),
        endTime: res.data.endTime.substr(0, 16),
        payType: res.data.payType,
        num: res.data.num,
        shopGroupId: res.data.shopGroupId,
        // shopId:res.data,
        price: res.data.price,
        detailImg: res.data.detailImg,
        sort: res.data.sort,
        couponList: list,
        cardList: res.data.vipList,
        cost: res.data.cost,
        name: res.data.name,
        shopGroupName: res.data.shopGroupName,
        goodsList: res.data.goodsList,
        useRules: res.data.useRules,
        activityRuleIndex: res.data.useRulesType
      })
      this.repeatList()
      this.repeatCardList()
    })
  },

  //修改排序值
  updateSort() {
    controller.updateSort({
      sort: this.data.sort,
      couponBagId: this.data.id
    }).then(res => {
      wx.showToast({
        icon: "none",
        title: '修改成功 ',
        duration: 1500
      })
      setTimeout(function () {
        wx.navigateBack()
      }, 1500)
    })
  },


  cancleBtn() {
    wx.navigateBack({
      delta: 0,
    })
  },
  saveBag() {

  },

  isAddBags() {
    const that = this
    wx.showModal({
      title: '是否确认提交',
      success: function (res) {
        if (res.confirm) {
          that.addBags()
        }
      }
    })
  },

  //新增券礼包
  addBags() {
    let value = {}
    let couponList = this.data.couponList
    let cardList = this.data.cardList
    value.useRules = this.data.useRules
    value.useRulesType = this.data.activitySelectList[this.data.activityRuleIndex].id
    value.payType = this.data.payType
    value.num = this.data.num
    value.type = this.data.type
    if (this.data.shopId) {
      value.shopId = this.data.shopId
    }
    value.shopGroupId = this.data.shopGroupId
    value.price = this.data.price
    value.cost = this.data.cost
    value.name = this.data.name
    value.sort = this.data.sort
    let shopList = []
    if (value.type === 0) {
      for (let i = 0; i < couponList.length; i++) {
        if (shopList.indexOf(couponList[i].shopId) == -1) {
          shopList.push(couponList[i].shopId)
        }
      }
      for (let i = 0; i < cardList.length; i++) {
        if (shopList.indexOf(cardList[i].shopId) == -1) {
          shopList.push(cardList[i].shopId)
        }
      }
      value.shopIds = shopList.join(",")
    } else {
      value.shopIds = this.data.shopId
    }
    value.img = this.data.img
    value.detailImg = this.data.detailImg
    value.startTime = this.data.startTime + ':00'
    value.endTime = this.data.endTime + ':00'
    let couponArrayJson = []
    let vipArrayJson = []
    for (let i = 0; i < couponList.length; i++) {
      let object = {}
      object.num = couponList[i].num
      object.couponId = couponList[i].id
      object.shopId = couponList[i].shopId
      object.sort = parseInt(couponList[i].sort)
      couponArrayJson.push(object)
    }
    for (let i = 0; i < cardList.length; i++) {
      let object = {}
      object.num = 1
      object.vipId = cardList[i].id
      object.shopId = cardList[i].shopId
      object.sort = parseInt(cardList[i].sort)
      vipArrayJson.push(object)
    }


    let haveSort = true
    couponArrayJson.forEach(item => {
      if (!item.sort) {
        haveSort = false
      }
    })
    if (haveSort === false) {
      wx.showToast({
        icon: "none",
        title: '请输入排序值',
        duration: 1500
      })
      return
    }
    value.couponArrayJson = JSON.stringify(couponArrayJson)

    let haveCardSort = true
    vipArrayJson.forEach(item => {
      if (!item.sort) {
        haveCardSort = false
      }
    })
    if (haveCardSort === false) {
      wx.showToast({
        icon: "none",
        title: '请输入排序值',
        duration: 1500
      })
      return
    }
    value.vipArrayJson = JSON.stringify(vipArrayJson)

    if (!value.num) {
      wx.showToast({
        icon: "none",
        title: '请填写库存数量',
        duration: 1500
      })
      return
    } else if (!value.shopGroupId) {
      wx.showToast({
        icon: "none",
        title: '请选择商圈',
        duration: 1500
      })
      return
    } else if (!value.price) {
      wx.showToast({
        icon: "none",
        title: '请输入价格',
        duration: 1500
      })
      return
    } else if (!value.name) {
      wx.showToast({
        icon: "none",
        title: '请输入名称',
        duration: 1500
      })
      return
    }
    // else if(!value.detailImg){
    //   wx.showToast({
    //     icon:"none",
    //     title: '请上传详情图',
    //     duration:1500
    //   })
    //   return
    // }
    else if (!value.startTime) {
      wx.showToast({
        icon: "none",
        title: '请选择活动开始时间',
        duration: 1500
      })
      return
    } else if (!value.endTime) {
      wx.showToast({
        icon: "none",
        title: '请选择活动结束时间',
        duration: 1500
      })
      return
    } else if (!value.couponArrayJson) {
      wx.showToast({
        icon: "none",
        title: '请选择添加商品/服务',
        duration: 1500
      })
      return
    } else if (!value.sort) {
      wx.showToast({
        icon: "none",
        title: '请输入排序值',
        duration: 1500
      })
      return
    } else if (!value.shopIds) {
      wx.showToast({
        icon: "none",
        title: '请选择商品/服务',
        duration: 1500
      })
      return
    }

    const otherValue = {
      repeatList: this.data.repeatList,
      repeatCardList: this.data.repeatCardList,
      shopGroupName: this.data.shopGroupName,
      couponList: this.data.couponList,
      cardList: this.data.cardList,
    }

    wx.navigateTo({
      url: './previewAddCouponBag?value=' + JSON.stringify(value) + '&otherValue=' + JSON.stringify(otherValue)
    })



    // controller.addBagSave(value).then(res => {
    //   if (res.code == 1) {
    //     wx.showToast({
    //       icon: "none",
    //       title: '添加成功',
    //       duration: 1000
    //     })
    //     setTimeout(function () {
    //       wx.redirectTo({
    //         url: '/pages/TradingAreaCenter/submitted',
    //       })
    //     }, 1000)
    //   }
    // })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */


  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // },

  //上传图片
  uploadImg() {
    if (this.data.isUpdata) {
      return
    }
    let that = this;
    wx.chooseImage({
      count: 1,
      success(res) {
        const tempFilePaths = res.tempFilePaths;
        const tempFiles = res.tempFiles;
        // if(tempFiles[0].size>1024*1024){
        //   wx.showToast({
        //     title: '单张图片大不能超过1MB',
        //     icon: 'none',
        //     duration: 2000
        //   })
        //   return
        // }
        wx.uploadFile({
          url: that.data.baseUrl + '/api/img/uploadFile',
          filePath: tempFilePaths[0],
          name: 'image',
          formData: {
            'sessionId': wx.getStorageSync("usertoken")
          },
          success(res) {
            console.log(res);
            let src = JSON.parse(res.data)
            that.setData({
              img: src.data
            })
          }
        })
      }
    })
  },

  //上传活动介绍详情图
  uploadDetailImg() {
    if (this.data.isUpdata) {
      return
    }
    let that = this;
    wx.chooseImage({
      count: 1,
      success(res) {
        const tempFilePaths = res.tempFilePaths;
        const tempFiles = res.tempFiles;
        if (tempFiles[0].size > 1024 * 1024 * 20) {
          wx.showToast({
            title: '单张图片大不能超过20MB',
            icon: 'none',
            duration: 2000
          })
          return
        }
        wx.uploadFile({
          url: that.data.baseUrl + '/api/img/uploadFile',
          filePath: tempFilePaths[0],
          name: 'image',
          formData: {
            'sessionId': wx.getStorageSync("usertoken")
          },
          success(res) {
            console.log(res);
            let src = JSON.parse(res.data)
            that.setData({
              detailImg: src.data
            })
          }
        })
      }
    })
  }
})